/*
    GPL

    ggets.h - Written by Diogo Sousa aka orium
    Copyright (C) 2006 Diogo Sousa

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/* Versão do ggets mais pequena, e que ocupa memos ram que a conhecida
 * versão de Falconer, mantendo a sua compactibilidade
 *
 * 29/07/2006, Diogo Sousa
 */

#ifndef _GGETS_H
#include <stdlib.h>
#include "debug.h"

#define ggets(str) fggets(str, stdin)

#define GGETS_INIT_SIZE 64
#define GGETS_EXPANSION_SIZE 16

#define GGETS_OK 0
#define GGETS_NOMEM 1
#define GGETS_EOF EOF

static int fggets(char **, FILE *) __attribute__ ((unused));

static int fggets(char **str, FILE *fp)
{
        int ch;
        long counter=0;
        long size;

        *str=NULL;

        if (feof(fp))
                return GGETS_EOF;

        *str=malloc(size=GGETS_INIT_SIZE);
        if (*str == NULL)
                return GGETS_NOMEM;

        while ((ch=fgetc(fp)) != EOF)
        {
                if (counter+1 >= size)
                        if ((*str=realloc(*str,size+=GGETS_EXPANSION_SIZE)) == NULL)
                                return GGETS_NOMEM;

                if (ch == '\n')
                        break;

                (*str)[counter]=ch;
                counter++;
        }

	(*str)[counter]='\0';

        return GGETS_OK;
}

#define _GGETS_H 1
#endif /*ggets.h included*/

/*EOF*/
